package edu.spec.chenli.Servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

//@WebServlet(name = "login",urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    //响应客户端请求的方法
    public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
        String errMsg = " ";
        //servlet本身并不输出响应到客户端，因此必须将请求转发到试图页面
        RequestDispatcher rd;
        //获取请求参数
        String username = request.getParameter("username");
        String pass= request.getParameter("password");
        try {
            DbDao dd = new DbDao("com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/1613580007", "root", "123456789");
            ResultSet rs = dd.query("SELECT pword FROM user_1" + "where uname=?", username);
            if (rs.next()) {
                if (rs.getString("pword").equals(pass)) {
                    HttpSession session = request.getSession(true);
                    session.setAttribute("uname", username);
                    rd = request.getRequestDispatcher("/processBuy.jsp");
                    rd.forward(request, response);
                } else {
                    errMsg += "你的用户密码不符合，请重新输入";

                }
            } else {
                errMsg += "你的用户不存在，请重新注册";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (errMsg !=null && !errMsg.equals("")){
            rd=request.getRequestDispatcher("/index.jsp");
            request.setAttribute("err",errMsg);
            rd.forward(request,response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
